
package com.shop.cloud.weixin.admin.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaMsgService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.weixin.admin.config.ma.WxMaConfiguration;
import com.shop.cloud.weixin.admin.config.mp.WxMpConfiguration;
import com.shop.cloud.weixin.common.constant.WxReturnCode;
import com.shop.cloud.weixin.common.dto.WxTemplateMsgSendDTO;
import com.shop.cloud.weixin.common.entity.WxTemplateMsg;
import com.shop.cloud.weixin.admin.mapper.WxTemplateMsgMapper;
import com.shop.cloud.weixin.admin.service.WxTemplateMsgService;
import com.shop.cloud.weixin.common.entity.WxUser;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 微信模板/订阅消息
 *
 * @author
 * @date 2020-04-16 17:30:03
 */
@Service
public class WxTemplateMsgServiceImpl extends ServiceImpl<WxTemplateMsgMapper, WxTemplateMsg> implements WxTemplateMsgService {

	/**
	 * 发送微信小程序订阅消息
	 * @param wxTemplateMsgSendDTO wxTemplateMsgSendDTO.useType、wxTemplateMsgSendDTO.page、wxTemplateMsgSendDTO.data、
	 * @param wxUser wxUser.appId、wxUser.openId、
	 */
	@Override
	public void sendWxMaTemplateMsg(WxTemplateMsgSendDTO wxTemplateMsgSendDTO, WxUser wxUser) {
		//查询订阅消息配置
		WxTemplateMsg wxTemplateMsg = baseMapper.selectOne(Wrappers.<WxTemplateMsg>lambdaQuery()
				.eq(WxTemplateMsg::getAppId,wxUser.getAppId())
				.eq(WxTemplateMsg::getEnable, CommonConstants.YES)
				.eq(WxTemplateMsg::getUseType,wxTemplateMsgSendDTO.getUseType()));
		if(wxTemplateMsg !=null){
			WxMaMsgService wxMaMsgService = WxMaConfiguration.getMaService(wxTemplateMsg.getAppId()).getMsgService();
			WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
			subscribeMessage.setToUser(wxUser.getOpenId());
			subscribeMessage.setTemplateId(wxTemplateMsg.getPriTmplId());
			subscribeMessage.setPage(wxTemplateMsgSendDTO.getPage());

			List<WxMaSubscribeMessage.MsgData> listData = new ArrayList<>();
			Map<String, Object> dataMap = wxTemplateMsgSendDTO.getData();
			wxTemplateMsg.getContent().forEach(content -> {
				WxMaSubscribeMessage.MsgData data = new WxMaSubscribeMessage.MsgData();
				JSONObject jSONObjectData = JSONUtil.parseObj(content);
				String name = jSONObjectData.getStr("name");
				data.setName(name);
				String attribute = jSONObjectData.getStr("attribute");
				Object ob = dataMap.get(attribute);
				if(ObjectUtil.isEmpty(ob)){
					ob = "无";
					if(StrUtil.contains(name, "character_string")){
						ob = "/";
					}
					if(StrUtil.contains(name, "amount")){
						ob = "0";
					}
					if(StrUtil.contains(name, "phone_number")){
						ob = "-";
					}
				}
				if(ob instanceof LocalDateTime){
					DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm");
					ob = ((LocalDateTime) ob).format(dtf);
				}
				String value = StrUtil.toString(ob);
				//最长20字节
				value = value.length() > 20 ? value.substring(0,19) : value;
				data.setValue(value);
				listData.add(data);
			});
			subscribeMessage.setData(listData);
			try {
				wxMaMsgService.sendSubscribeMsg(subscribeMessage);
			} catch (WxErrorException e) {
				if(!WxReturnCode.ERR_43101.getCode().equals(e.getError().getErrorCode()+"")){
					log.error(e.getMessage(),e);
				}
			}
		}
	}

	/**
	 * 发送微信公众号模板消息
	 * @param wxTemplateMsgSendDTO wxTemplateMsgSendDTO.useType、wxTemplateMsgSendDTO.page、wxTemplateMsgSendDTO.data、
	 * @param wxUser wxUser.appId、wxUser.openId、
	 */
	@Override
	public void sendWxMpTemplateMsg(WxTemplateMsgSendDTO wxTemplateMsgSendDTO, WxUser wxUser) {
		//查询模板消息配置
		WxTemplateMsg wxTemplateMsg = baseMapper.selectOne(Wrappers.<WxTemplateMsg>lambdaQuery()
				.eq(WxTemplateMsg::getAppId,wxUser.getAppId())
				.eq(WxTemplateMsg::getEnable, CommonConstants.YES)
				.eq(WxTemplateMsg::getUseType,wxTemplateMsgSendDTO.getUseType()));
		if(wxTemplateMsg !=null){
			WxMpTemplateMsgService wxMpTemplateMsgService = WxMpConfiguration.getMpService(wxTemplateMsg.getAppId()).getTemplateMsgService();
			WxMpTemplateMessage subscribeMessage = new WxMpTemplateMessage();
			subscribeMessage.setToUser(wxUser.getOpenId());
			subscribeMessage.setTemplateId(wxTemplateMsg.getPriTmplId());
			if(StrUtil.isNotBlank(wxTemplateMsg.getMaAppId())){
				WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
				miniProgram.setAppid(wxTemplateMsg.getMaAppId());
				miniProgram.setPagePath(wxTemplateMsgSendDTO.getPage());
				subscribeMessage.setMiniProgram(miniProgram);
			}
			List<WxMpTemplateData> listData = new ArrayList<>();
			Map<String, Object> dataMap = wxTemplateMsgSendDTO.getData();
			wxTemplateMsg.getContent().forEach(content -> {
				WxMpTemplateData data = new WxMpTemplateData();
				JSONObject jSONObjectData = JSONUtil.parseObj(content);
				String name = jSONObjectData.getStr("name");
				data.setName(name);
				data.setColor(jSONObjectData.getStr("color"));
				String attribute = jSONObjectData.getStr("attribute");
				Object ob = dataMap.get(attribute);
				if(ObjectUtil.isEmpty(ob)){
					ob = "无";
					if(StrUtil.contains(name, "character_string")){
						ob = "/";
					}
					if(StrUtil.contains(name, "amount")){
						ob = "0";
					}
					if(StrUtil.contains(name, "phone_number")){
						ob = "-";
					}
				}
				if(ob instanceof LocalDateTime){
					DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm");
					ob = ((LocalDateTime) ob).format(dtf);
				}
				String value = StrUtil.toString(ob);
				//最长20字节
				value = value.length() > 20 ? value.substring(0,19) : value;
				data.setValue(value);
				listData.add(data);
			});
			subscribeMessage.setData(listData);
			try {
				wxMpTemplateMsgService.sendTemplateMsg(subscribeMessage);
			} catch (WxErrorException e) {
				if(!WxReturnCode.ERR_43101.getCode().equals(e.getError().getErrorCode()+"")){
					log.error(e.getMessage(),e);
				}
			}
		}
	}
}
